public class BalancedBinaryTree {
    public class TreeNode{
        int val;
        TreeNode left;
        TreeNode right;
        TreeNode(){}
        TreeNode(int val){
            this.val = val;
        }
    }
    public boolean isBalanced(TreeNode root) {
        if(root == null){
            return true;
        }
        //判断左子树是否为平衡二叉树
        int leftH = getHeight(root.left);
        //判断右子树是否为平衡二叉树
        int rightH = getHeight(root.right);
        //当满足三个条件时返回ture
        return Math.abs(leftH-rightH)<2&&isBalanced(root.left)&&isBalanced(root.right);
    }
    //获取树的高度
    public int getHeight(TreeNode root){
        if(root == null){
            return 0;
        }
        //获取左子树高度
        int leftH = getHeight(root.left);
        //获取右子树高度
        int rightH = getHeight(root.right);
        //返回左右子树的最大值+1（加上根节点高度），即为树的高度
        return ((leftH > rightH) ? (leftH+1):(rightH+1));
    }
}
